﻿using System;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.UI;
using AjaxChatWebApp.DTO;

namespace AjaxChatWebApp.Account
{
    public partial class Register : Page
    {
        HttpClient httpClient = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            httpClient.BaseAddress = new Uri("http://localhost:62865");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        protected void btReg_Click(object sender, EventArgs e)
        {
            var user = GetUserInfo();
            HttpResponseMessage response = httpClient.PostAsJsonAsync("api/users", user).Result;
            if(response.IsSuccessStatusCode)
            {
                UploadAvatar();
                user = response.Content.ReadAsAsync<User>().Result;
                Session["IsLogin"] = true;
                Session["UserId"] = user.Id;
                Session["UserName"] = user.UserName;
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                ErrorMessage.Text = "This username has been used. Please choose another username";
            }
        }

        private User GetUserInfo()
        {
            string fileName = "defaultAvatar.png";
            if (fuAvatar.HasFile)
                fileName = fuAvatar.FileName;

            var user = new User
            {
                UserName = tbUserName.Text,
                FirstName = tbFirstName.Text,
                LastName = tbLastName.Text,
                Password = tbPassword.Text,
                Status = true,
                Avatar = fileName
            };

            return user;
        }

        private void UploadAvatar()
        {
            if(fuAvatar.HasFile)
            {
                string desPath = Server.MapPath("~/Avatars/" + fuAvatar.FileName);
                fuAvatar.SaveAs(desPath);
            }
        }
    }
}